package ClientD;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.DecimalFormat;
import java.util.List;
import java.util.Objects;

/**
 * 超市
 */
public class Shop{

    public <T extends Fruit> T createFruit(Class<T> fruitClass, String num, DiscountStrategy discountStrategy) {
        try {
            return (T) Class.forName(fruitClass.getName())
                    .getConstructor(String.class, DiscountStrategy.class) // 接收参数
                    .newInstance(num, discountStrategy);    // 实际参数
        } catch (Exception e) {
            throw new RuntimeException("Error creating fruit instance", e);
        }
    }

    public String calculateTotalPrice(List<Fruit> fruits){
        if(Objects.isNull(fruits) || fruits.size() == 0){
            return "无购买商品";
        }

        BigDecimal totalPrice = new BigDecimal(BigInteger.ZERO);
        DecimalFormat decimalFormat = new DecimalFormat("#.00"); // 格式化
        for (Fruit fruit : fruits) {
            BigDecimal payCount = fruit.payCount();
            totalPrice = totalPrice.add(payCount);
        }
        return "总共消费："+decimalFormat.format(coupon(totalPrice));
    }

    private BigDecimal coupon(BigDecimal totalPrice){
        System.out.println("判断是否符合优惠卷条件：100 减 10 块");
        if(totalPrice.compareTo(new BigDecimal("100")) == 1){
            totalPrice =  totalPrice.add(new BigDecimal("-10"));
            System.out.println("符合优惠条件，优惠了10元");
        }
        return totalPrice;
    }

}
